package org.codeart.driver.service;

import org.codeart.common.response.TerminalResponse;
import org.codeart.common.response.TraceResponse;
import org.codeart.common.util.R;
import org.codeart.driver.mapper.CarMapper;
import org.codeart.common.dto.Car;
import org.codeart.driver.remote.ServiceMapClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class CarService {
    
    @Autowired
    private ServiceMapClient serviceMapClient;
    
    @Autowired
    private CarMapper carMapper;
    
    @Transactional
    public boolean addCar(Car car) {
        LocalDateTime now = LocalDateTime.now();
        car.setGmtCreate(now).setGmtModified(now);
        int i = carMapper.insert(car);
        if (i == -1) {
            return false;
        }
        
        // 获得此车辆的终端id tid
        R<TerminalResponse> r = serviceMapClient.addTerminal(car.getVehicleNo(), car.getId() + "");
        Integer tid = r.getData().getTid();
        car.setTid(tid);
        
        // 获得此车辆的轨迹id trid
        R<TraceResponse> r1 = serviceMapClient.addTrace(tid);
        TraceResponse data = r1.getData();
        Integer trid = data.getTrid();
        String trname = data.getTrname();
        car.setTrid(trid).setTrname(trname);

        int j = carMapper.updateById(car);
        return j != -1;
    }
    
    public Car getCarById(Long carId) {
        return carMapper.selectById(carId);
    }

}
